package dao;

import utils.DBHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PhoneManageDao {

    public Map<String, Object> query(String product, String type, String begin, String end, int page, int size){
        String sql = "select * from plist where status=1 ";
        List<Object> params = new ArrayList<>();

        if (product != null && product.trim().isEmpty() == false){
            sql += " and product like ? ";
            params.add("%" + product + "%");
        }
        if (type != null && type.trim().isEmpty() == false){
            sql += " and type like ? ";
            params.add("%" + type + "%");
        }
        if (begin != null && begin.trim().isEmpty() == false) {
            sql += " and price >= ? ";
            params.add(begin);
        }
        if (end != null && end.trim().isEmpty() == false) {
            sql += " and price <= ? ";
            params.add(end);
        }
        long total = DBHelper.count(sql, params.toArray());

        // 分页查询 第几行开始查 查多少行
        sql += " limit ?, ? ";
        params.add(size * (page - 1));
        params.add(size);
        List<Map<String,Object>> data = DBHelper.selectListMap(sql, params.toArray());
        Map<String, Object> res = new HashMap<>();
        res.put("total", total);
        res.put("data", data);
        return res;
    }

    public int exists(String product){
        String sql = "select product from plist where product = ? ";
        if (DBHelper.selectOneMap(sql, product) == null){
            return 0;
            // 返回 0 则表示不存在数据
        }
        return 1;
        // 返回 1 则表示存在
    }

    public void create(String product, String price, String count, String type,String intro, String image, String color){
        String sql = "insert into plist ( product, price, count, type,intro, image, color)" +
                "values (?, ?, ?, ?, ?, ?, ?)";
        DBHelper.update(sql,product, price, count, type,intro, image, color);
    }

    public void modify(String id, String product, String price, String count, String type,String intro, String image, String color){
        String sql = "update plist set product=?, price=?, count=?, type=?, intro=?, image=?, color=? where id=?";
        DBHelper.update(sql,product,price, count, type, intro, image, color, id);
    }

    public void remove(String id){
        String sql = "delete from plist where id=? ";
        DBHelper.update(sql, id);
    }
    public void remove1(String id){
        String sql = "update plist set status=0 where id=?";
        DBHelper.update(sql,id);
    }
}
